// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV })

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  const db = cloud.database()
  const orders = db.collection('orders')
  const openid = wxContext.OPENID

  try {
    const { orderId, address, remark } = event
    console.log( orderId, address, remark )
    if (!orderId) {
      return {
        success: false,
        message: '订单ID不能为空'
      }
    }

    // 查询订单信息
    const orderRes = await orders.doc(orderId).get()
    
    if (!orderRes.data) {
      return {
        success: false,
        message: '订单不存在'
      }
    }

    // 检查订单是否属于当前用户
    if (orderRes.data._openid !== openid) {
      return {
        success: false,
        message: '无权修改此订单'
      }
    }

    // 更新订单信息
    const updateData = {
      updated_at: new Date()
    }
    
    if (address) {
      updateData.address = address
    }
    
    if (remark !== undefined) {
      updateData.remark = remark
    }

    await orders.doc(orderId).update({
      data: updateData
    })

    return {
      success: true,
      message: '订单更新成功'
    }
  } catch (error) {
    console.error('更新订单失败：', error)
    return {
      success: false,
      message: '更新订单失败'
    }
  }
} 